package com.dong.dingtalk_demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class DingTalkUtil {

    private static OkHttpClient mClient;
    private static String url;
    //初始化客户端

    @Value("${baseUrl}")
    private String baseUrl;
    @Value("${token}")
    private String token; //钉钉官方所获取的token
    @Value("${secret}")
    private String secret; //前期准备中的加签

    @PostConstruct
    public void initClient(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10L, TimeUnit.SECONDS);
        builder.readTimeout(10L, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(200);
        dispatcher.setMaxRequests(200);
        builder.dispatcher(dispatcher);
        mClient = builder.build();
        try {
            url = getSign();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用 POST 请求方法  依赖 OKhttp3
     * @param message 所要发送的消息
     * @return 发送状态回执
     */
    public static String postWithJson(String message,Integer num) {
        JSONObject propertiesObj = new JSONObject();
        Map<String,Object> atMap = new HashMap<>();
        Map<String,Object> contentMap = new HashMap<>();
//        List<String> mobiles = new ArrayList();
//        mobiles.add("15958130313");
////        if (num == 0){
////            mobiles.add("15711459260");
////        }else if (num == 1){
////            mobiles.add("15958130313");
////        }else {
////            mobiles.add("18658120620");
////        }
        atMap.put("isAtAll",true);
       // atMap.put("atMobiles",mobiles);
        propertiesObj.put("at",atMap);
        contentMap.put("content","%s");
        propertiesObj.put("text",contentMap);
        propertiesObj.put("msgtype","text");
        //String str="{ \"at\": { \"isAtAll\": false, \"atMobiles\": [\"15711459260\"] }, \"text\": { \"content\": \" %s \"}, \"msgtype\":\"text\" }"; //这里@为全体成员，可具体@某个人只需加上手机号即可
        String format = String.format(propertiesObj.toJSONString(), message);
        JSONObject jsonObject = JSON.parseObject(format);
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取签名
     * @return 返回签名
     */
    private  String getSign() throws Exception {
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return baseUrl + token + "&timestamp=" + timestamp + "&sign=" +
                URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }
}
